package com.yhj.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yhj.reggie.dto.OrdersDto;
import com.yhj.reggie.entity.*;
import com.yhj.reggie.mapper.*;
import com.yhj.reggie.service.OrderService;
import com.yhj.reggie.util.UUIDUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired(required = false)
    private AddressBookMapper addressBookMapper;
    /*id          bigint auto_increment comment '主键'
        primary key,
    name        varchar(50)    null comment '名称',
    image       varchar(100)   null comment '图片',
    user_id     bigint         not null comment '主键',
    dish_id     bigint         null comment '菜品id',
    setmeal_id  bigint         null comment '套餐id',
    dish_flavor varchar(50)    null comment '口味',
    number      int default 1  not null comment '数量',
    amount      decimal(10, 2) not null comment '金额',
    create_time datetime       null comment '创建时间'*/
    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired(required = false)
    private UserMapper userMapper;
    @Autowired(required = false)
    private OrderDetailMapper orderDetailMapper;
    @Autowired(required = false)
    private OrderMapper orderMapper;
    /**
     * 下订单,新建订单
     *
     * @param orders
     * @param userId
     */
    @Override
    public void addOrder(Orders orders, Long userId) {
        //1.通过地址对象id找到地址
        /*create table address_book
(
    id            bigint auto_increment comment '主键'
        primary key,
    user_id       bigint                       not null comment '用户id',
    consignee     varchar(50)                  not null comment '收货人',
    sex           tinyint                      not null comment '性别 0 女 1 男',
    phone         varchar(11)                  not null comment '手机号',
    province_code varchar(12) charset utf8mb4  null comment '省级区划编号',
    province_name varchar(32) charset utf8mb4  null comment '省级名称',
    city_code     varchar(12) charset utf8mb4  null comment '市级区划编号',
    city_name     varchar(32) charset utf8mb4  null comment '市级名称',
    district_code varchar(12) charset utf8mb4  null comment '区级区划编号',
    district_name varchar(32) charset utf8mb4  null comment '区级名称',
    detail        varchar(200) charset utf8mb4 null comment '详细地址',
    label         varchar(100) charset utf8mb4 null comment '标签',
    is_default    tinyint(1) default 0         not null comment '默认 0 否 1是',
    create_time   datetime                     not null comment '创建时间',
    update_time   datetime                     not null comment '更新时间',
    create_user   bigint                       not null comment '创建人',
    update_user   bigint                       not null comment '修改人',
    is_deleted    int        default 0         not null comment '是否删除'
)
    comment '地址管理' collate = utf8_bin;
*/
        AddressBook addressBook = addressBookMapper.getById(orders.getAddressBookId());
        //2.通过用户id找到购物车列表
        /*id          bigint auto_increment comment '主键'
        primary key,
    name        varchar(50)    null comment '名称',
    image       varchar(100)   null comment '图片',
    user_id     bigint         not null comment '主键',
    dish_id     bigint         null comment '菜品id',
    setmeal_id  bigint         null comment '套餐id',
    dish_flavor varchar(50)    null comment '口味',
    number      int default 1  not null comment '数量',
    amount      decimal(10, 2) not null comment '金额',
    create_time datetime       null comment '创建时间'*/
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.findAllByUser(userId);
        //3.通过用户id找到User对象,获取用户别名
        User user = userMapper.findByid(userId);
        //4.完善订单数据
        Long oid = new Long(UUIDUtils.getUUIDInOrderId());
        orders.setId(oid);
        orders.setNumber(oid+"");
        orders.setStatus(1);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());

        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());

        //完善订单详情
        ArrayList<OrderDetail> orderDetailList=new ArrayList<>();
        //定义总金额
        BigDecimal total = new BigDecimal("0");
        //遍历购物车列表,复制数据到订单详情列表
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail od = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,od);
            od.setId(new Long(UUIDUtils.getUUIDInOrderId()));
            od.setOrderId(orders.getId());

            orderDetailList.add(od);

            total=total.add(od.getAmount().multiply(new BigDecimal(od.getNumber()+"")));
        }

        orders.setAmount(total);

        orderDetailMapper.saveOrderDetail(orderDetailList);
        orderMapper.save(orders);



        shoppingCartMapper.deleteAll(userId);
    }

    /**
     * 查找所有订单
     *
     * @param page
     * @param pageSize
     * @param userId
     * @return
     */
    @Override
    public Page<OrdersDto> findByUser(Integer page, Integer pageSize, Long userId) {

        PageHelper.startPage(page,pageSize);
        List<OrdersDto> ordersDtoList = orderMapper.findAll(userId);
        PageInfo<OrdersDto> ordersDtoPageInfo = new PageInfo<>(ordersDtoList);

        Page<OrdersDto> newPage = new Page<>();
        newPage.setRecords(ordersDtoPageInfo.getList());
        newPage.setTotal(ordersDtoPageInfo.getTotal());


        return newPage;
    }
}
